package com.example.lj.uav.view.base;

import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;

import com.example.lj.uav.service.FlightRecorderService;
import com.example.lj.uav.utils.OnUIUtils;

public class BaseActivity extends AppCompatActivity {


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //无title
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        //全屏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
    }

    @Override
    protected void onResume() {
        /**
         * 设置为横屏
         */
        if (getRequestedOrientation() != ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        }

        super.onResume();
    }

    public void toAct(Class<?> clazz) {
        toAct(clazz, false);
    }

    public void toAct(Class<?> clazz, boolean isFinish) {
        startActivity(new Intent(this, clazz));
        if (isFinish) {
            finish();
        }
    }

    public void toAct(Class<?> clazz, String flag) {
        Intent intent = new Intent(this, clazz);
        intent.putExtra("FLAG", flag);
        startActivity(intent);
    }

    public String getFlag() {
        return getIntent().getStringExtra("FLAG");
    }

    protected void showToast(String str) {
        OnUIUtils.setToast(str);
//        Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
    }

    protected void showToastOnUi(final Context context, final String msg) {
        runOnUiThread(new Runnable() {
            public void run() {
                Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
            }
        });
    }

    private long exitTime;
    private boolean isLastActivity = false;

    protected void backToExit() {
        isLastActivity = true;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (isLastActivity) {
            if (keyCode == KeyEvent.KEYCODE_BACK) {
                if ((System.currentTimeMillis() - exitTime) > 2000) {
                    Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
                    exitTime = System.currentTimeMillis();
                } else {
                    stopService(new Intent(this, FlightRecorderService.class));
                    System.exit(0);
                }
                return true;
            }
        } else
            finish();
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {

        super.onDestroy();
    }
}
